/*
Copyright 2010-2011 CumulusCloud
http://cumuluscloud.cc

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package appmanager.server.appstore.runner;

import java.io.File;
import java.io.IOException;
import java.util.logging.Logger;

import appmanager.server.appstore.AppStore;

public class UpdateAppListRun extends Downloader {
	private static Logger logger = Logger.getLogger(UpdateAppListRun.class.getName());
	private File destinationFile;
	
	public UpdateAppListRun(File destinationFile) {
		this.destinationFile = destinationFile;
	}
	
	@Override
	public String getName() {
		return "Update App List";
	}

	@Override
	public void run() {
		logger.info("Starting updating app list");
		
		// Create temp file
		File tmp = null;
		try {
			tmp = File.createTempFile("download", null);
		} catch (IOException e) {
			e.printStackTrace();
			setFinalStatus("ERROR creating temp file");
			return;
		}
		
		// Download the file
		setStatus("Downloading app list");
		if (!downloadUrl("http://cumuluscloudappstore.appspot.com/ApplicationList", tmp, 3)) {
			setFinalStatus("ERROR getting list");
			return;
		}
		
		// Move and load
		logger.info("Move the complete file and update the list");
		setStatus("Loading the new file");
		destinationFile.delete();
		tmp.renameTo(destinationFile);
		AppStore.getInstance().loadAppFileList(false);
		
		setFinalStatus("SUCCESS");
	}
}
